package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.AppUserLoginService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

/**
 * @authar by xiecong
 * @Date 2022/3/7
 * @Description
 */
@Service
public class AppUserLoginServiceImpl implements AppUserLoginService {

    @Autowired
    ApUserMapper apUserMapper;

    /**
     * App端登陆
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDTO dto) {
        //1.用户登陆
        // 1.1参数校验
        String phone = dto.getPhone();
        String pwd = dto.getPassword();
        if (StringUtils.isNotBlank(phone) && StringUtils.isNotBlank(pwd)) {
            //如果不为空，数据库查询一个用户信息
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery()
                    .eq(ApUser::getPhone, dto.getPhone()));
            //判断
            if (apUser == null) {
                CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"相关用户不存在");
            }
            //1.2获取数据库密码
            String password = apUser.getPassword();
            //输入的密码+盐salt
            String newPwd = DigestUtils.md5DigestAsHex((pwd + apUser.getSalt()).getBytes());
            //1.3判断输入的密码和数据库密码是否相等
            if (!password.equals(newPwd)) {
                CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //1.4校验用户的状态
            if (apUser.getStatus()){
                CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"用户状态锁定");
            }
            //1.4封装返回结果
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(Long.valueOf(apUser.getId())));
            map.put("user",apUser);
            return ResponseResult.okResult(map);
        }else {
            //2.用户不登陆
            if (dto.getEquipmentId()==null){
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"设备id不存在");
            }
            HashMap<String, Object> map = new HashMap<>();
            //通过设备id登陆，userId设置为0
            String token = AppJwtUtil.getToken(0L);
            map.put("token",token);
            return ResponseResult.okResult(map);
        }
    }
}
